import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:myapp/globle/route_manager.dart';
import 'package:myapp/ui/item/item_article_widget_1.dart';
import 'package:myapp/util/colors_utils.dart';
import 'package:myapp/view_model/home_page_model.dart';
import 'package:myapp/widget/provider_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'item/item_article_widget_2.dart';

const int HOT = 0;
const int NEWEST = 1;
const int SQUARE = 2;
const int PROJECT = 3;
const int ARTICLE = 4;

class HomePage extends StatefulWidget {
  const HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class PopularPage extends StatefulWidget {
  final int type;

  const PopularPage(this.type);

  @override
  State<StatefulWidget> createState() => _PopularPageState();
}

class _PopularPageState extends State<PopularPage> with AutomaticKeepAliveClientMixin {
  _PopularPageState();

  RefreshController _refreshController =
      RefreshController(initialRefresh: true);
  @override
  bool get wantKeepAlive => true;

  Future<void> _onRefresh(model) async {
    await model.refresh();
    _refreshController.refreshCompleted();
    if (model.isLoadMore) {
      _refreshController.resetNoData();
    }
  }

  Future<void> _onLoading(model) async {
    await model.loadMore();
    if (model.isLoadMore) {
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  Widget _getTag(HomePageModel model) {
    var tags = model.getTags;
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10),
      margin: EdgeInsets.only(bottom: 1),
      child: SizedBox(
          height: 26,
          child: ListView.separated(
              itemCount: tags.length,
              separatorBuilder: (context, index) => VerticalDivider(
                    width: 12,
                    color: Colors.transparent,
                  ),
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) => InkWell(
                    child: Container(
                      child: Center(
                          child: Padding(
                        child: Text(
                          tags[index].name,
                        ),
                        padding: EdgeInsets.symmetric(horizontal: 10),
                      )),
                      decoration: BoxDecoration(
                          color: model.cid == tags[index].id
                              ? ColorUtils.color_bg_3
                              : ColorUtils.color_bg_2,
                          borderRadius: BorderRadius.circular(24)),
                    ),
                    onTap: () {
                      model.chooseTag(tags[index].id);
                      _refreshController.requestRefresh();
                    },
                  ))),
      color: ColorUtils.color_bg_1,
    );
  }

  @override
  Widget build(BuildContext context) {
    return ProviderWidget<HomePageModel>(
      model: HomePageModel(widget.type),
      onModelInit: (model) {},
      builder: (BuildContext context, HomePageModel model, Widget child) =>
          Column(children: [
        if (widget.type == PROJECT || widget.type == ARTICLE) _getTag(model),
        Expanded(
            flex: 1,
            child: SmartRefresher(
                controller: _refreshController,
                enablePullDown: true,
                header: WaterDropHeader(),
                enablePullUp: model.getArticles.isNotEmpty,
                physics: BouncingScrollPhysics(),
                onRefresh: () => _onRefresh(model),
                onLoading: () => _onLoading(model),
                child: ListView.separated(
                  separatorBuilder: (context, index) => Divider(height: 4),
                  itemCount: model.getArticles.length,
                  itemBuilder: (context, index) {
                    var article = model.getArticles[index];
                    return (widget.type == SQUARE || widget.type == ARTICLE)
                        ? ItemArticleWidget2(
                            article: article,
                          )
                        : ItemArticleWidget1(
                            article: article,
                          );
                  },
                )))
      ]),
    );
  }
}

class _HomePageState extends State<HomePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  List<Tab> _tabs = [
    Tab(text: "热门"),
    Tab(text: "最新"),
    Tab(text: "广场"),
    Tab(text: "项目"),
    Tab(text: "公众号"),
  ];

  @override
  bool get wantKeepAlive => true;

  List<Widget> _pages = [
    PopularPage(
      HOT,
    ),
    PopularPage(
      NEWEST,
    ),
    PopularPage(
      SQUARE,
    ),
    PopularPage(
      PROJECT,
    ),
    PopularPage(
      ARTICLE,
    )
  ];
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    print("HomePage initState");
    _tabController = TabController(length: _tabs.length, vsync: this);
  }

  void _chooseTap(int tab) {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: GestureDetector(
            onTap: () => {Navigator.pushNamed(context, RouteName.SEARCH_PAGE)},
            child: Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Padding(
                        child: Icon(
                          Icons.search,
                          color: ColorUtils.color_text_3,
                          size: 16,
                        ),
                        padding: EdgeInsets.only(right: 4, left: 10)),
                    Text("搜索",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: 14, color: ColorUtils.color_text_3))
                  ],
                ),
                width: double.infinity,
                height: 40,
                decoration: new BoxDecoration(
                  color: ColorUtils.color_bg_3,
                  borderRadius: BorderRadius.all(Radius.circular(32)),
                ))),
        bottom: TabBar(
          indicatorColor: ColorUtils.color_text_1,
          tabs: _tabs,
          controller: _tabController,
          onTap: _chooseTap,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _pages,
      ),
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("HomePage didChangeDependencies");
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("HomePage didChangeAppLifecycleState" + state.toString());
  }

  @override
  void deactivate() {
    super.deactivate();
    print("HomePage deactivate");
  }

  @override
  void dispose() {
    super.dispose();
    _tabController?.dispose();
    print("HomePage dispose");
  }
}
